/**
 * 万年历看板 节日数据 折线图
 */
define(function(){
    var ec=require('echarts');
    require('echarts/chart/line');
    require('echarts/chart/bar');

    var myChart = ec.init(document.getElementById('seasonSource_EC_m'));
    var option_day = {
        tooltip : {
            trigger: 'axis',
            formatter:tooltipFunc
        },
        legend: {
            data:[]
        },
        toolbox: {
            show : true,
            orient:'vertical',
            feature : {
                mark : {show: true},
                dataZoom : {show: true},
                magicType : {show: true, type: ['line', 'bar']},
                restore : {show: true},
                saveAsImage : {show: true}
            }
        },
        calculable : true,
        grid: {
            y:45
        },
        xAxis: [{
            type: "category",
            boundaryGap: true,
            data:[''],
            axisLabel:{
                formatter:function(value){
                return value;
                }
            }
        }],
        yAxis: [],
        dataZoom: {
            show: true,
            start: 90
        },
        series: []
    };
    
    var trueTimejson="";
    var truedatajson='';
	var festivaldatajson='';
    /**
     * 根据指标显示日数据
     * @param eventType= 2:第一次加载, 1:切换日，周刷新
     */
    function show(infoTrend,eventType){
        var dateGrp = $('#SeasonSourceOption_m').attr('dateGrp');      
        var cate_option = $('#cate_option').val();
        var source_option = $('#source_option_m').val();
        var index_Type = $('#index_Type').val();
       
		var platform ='m';
				
        myChart.showLoading({
            text: '正在努力的读取数据中...'
        });
        $.ajax({
            url: '/dashboard/calendar/ajax/getSeasonSourceLine',
            type: 'post',
            async: true,    
            data:{"businessName":businessName, "dateGroup":dateGrp,"cate_option":cate_option,"source_option":source_option,"platform":platform,"index_Type":index_Type},
            dataType: 'json',
            timeout:5000,
            success: function(data, textStatus) {
            	
            	if(data.time==null)
	            {
	                 myChart.showLoading({
                     text: '您好，所筛选情况暂无数据...'
                     });
	            }
	            else 
	            { 
	                option_day.xAxis[0].data = data.time;
	                option_day.legend.data = data.legend;
	
	                truedatajson=data.truedatajson;
	   				festivaldatajson=data.festivaldatajson;
	                trueTimejson=data.trueTimejson;
	
	                var series_local = [];
	                for(var i=0;i<data.legend.length;i++){
	                    series_local[i] = {
	                        name: data.legend[i],
	                        type: 'line',
	                        yAxisIndex: 0,
	                        smooth: true,
	                        symbol:'none',                   
	                        "data":  data[data.legend[i]]  
	                    }
	                }
					
	                option_day.series = series_local;
	                    //区域缩放重置      
	                 var datezoom_local={
	                        stat_date:{start:0,end:100},
	                        week_begin:{start:0,end:100},
	                        month_num:{start:0,end:100}
	                    };  
	            
	               if(eventType == 1 || eventType == 2){
	                    if('stat_date'==dateGrp){
	                        option_day.series.forEach(function(value){
	                            value.type='line';
	                        });                 
	                        option_day.xAxis[0].axisLabel.formatter=function(value){
	                            return value;
	                        }
	                    }else if('week_begin'==dateGrp){
	                        option_day.series.forEach(function(value){
	                            value.type='line';
	                        });
	                        option_day.xAxis[0].axisLabel.formatter=function(value){
	                            return value;
	                        }
	                    }else if('month_num'==dateGrp){
	                        option_day.series.forEach(function(value){
	                            value.type='line';
	                        });
	                        option_day.xAxis[0].axisLabel.formatter=function(value){
	                            return value.substr(0,4)+"年"+value.substr(4,2)+"月";
	                        }
	                    }
	                    if(eventType == 1 && myChart.component.dataZoom){
	                        option_day.dataZoom=datezoom_local[dateGrp];
	                        myChart.component.dataZoom.absoluteZoom(datezoom_local[dateGrp]);
	                        option_day.dataZoom.show=true;
	                    }else if(eventType == 2){
	                        option_day.dataZoom=datezoom_local[dateGrp];
	                        option_day.dataZoom.show=true;
	                    }
	                    myChart.setOption(option_day,true);
	                }else if(eventType == 0){
	                    myChart.component.dataZoom=compDataZoom_old;
	                    option_day.dataZoom.show=true;
	                    myChart.setOption(option_day,true);
	                }
	
	                myChart.hideLoading();
	            }
            },
            error : function() {
                myChart.hideLoading();
            }
        });
    }


   //提示框
    function  tooltipFunc(params, ticket, callback,showType){
    	//以去年来计算index_current，因为横坐标为去年
    	var curname="";
        if(params.length==1)
		{
			curname=params[0].name;
		}
		else if(params.length>1)
		{
		    curname=params[params.length-2].name;
		}		    	
        var index_current=getIndexByName(option_day.xAxis[0].data,curname);

        var result='<table class="table-center">';
        result+='<tr><td>日期</td>';
        var isStatDay = isDay(); 
        result +="<td>真实值</td>";
       
        if(isStatDay)
            result +="<td>日环比</td><td>周同比</td>";
        else if(isWeek())
            result += "<td>周环比</td>";
         else if(isMonth())
            result += "<td>月环比</td>";
		if(!isMonth())
		{
			result += "<td>节日标记</td>";
		}
        result += '</tr>';       
       
        $(params).each(function(index,para){
		    //如果那年在当天的数没有     		
        	if(trueTimejson[para.seriesName].length<=index_current)
        	{
        		return true;
        	}       	
            var curdate=formatShowDate(trueTimejson[para.seriesName][index_current]);      	
        	//如果是补的预测值
        	var cur=truedatajson[para.seriesName][index_current];         
            if(cur=="")
        	{
        		return true;
        	}
        	
            if(isMonth())//月不加星期
            {
            	result+='<tr><td>'+curdate+'</td><td>';
            }
            else
				result+='<tr><td>'+curdate+'('+getWeekDay(curdate)+')</td><td>';
				result+=zrnumber.addCommas(truedatajson[para.seriesName][index_current])+'</td>';

            var seriesIndex = para.seriesIndex;
            var day_td="<td>--</td>";
            //环比
            if(index_current-1>=0){
                var data_yesday = null;
                data_yesday= option_day.series[seriesIndex].data[index_current-1];                
                if(data_yesday != null){
                    var s=(((para.data/data_yesday)-1)*100).toFixed(2);
                    if(s>0){
                        day_td='<td style="color: orangered;">'+s+'%&#8593</td>';
                    }else{
                        day_td='<td style="color: greenyellow;">'+s+'%&#8595</td>';
                    }
                }
            }
            result += day_td;
            //周同比
            if(isStatDay){
                var week_td='<td></td>';
                if(index_current-7>=0){
                    data_week= option_day.series[seriesIndex].data[index_current-7];
                    var s=(((para.data/data_week)-1)*100).toFixed(2);
                    if(s>0){
                        week_td='<td style="color: orangered;">'+s+'%&#8593</td>';
                    }else{
                        week_td='<td style="color: greenyellow;">'+s+'%&#8595</td>';
                    }
                }
                result += week_td;
            }
			 if(!isMonth())
			{
				 if(festivaldatajson[para.seriesName][index_current]!="NULL")
           		 {
            		result+='<td>'+festivaldatajson[para.seriesName][index_current]+'</td>';
           		 }else result+='<td>--</td>';
			}
            result += '</tr>';
        });
        result+='</table>';
        return result;
    }   
    
    var zrnumber = require('echarts/util/number');

	function formatShowDate(yyyymmdd){
        var dateGrp = $('#SeasonSourceOption_m').attr('dateGrp');
        if('stat_date'==dateGrp){
            return yyyymmdd;
        }else if('week_begin'==dateGrp){
            return yyyymmdd;
        }else if('month_num'==dateGrp){
            return yyyymmdd.substr(0,4)+"年"+yyyymmdd.substr(4,2)+"月";
        }
    }

    function isDay(){
        var dateGrp = $('#SeasonSourceOption_m').attr('dateGrp');
        if('stat_date'==dateGrp){
            return true;
        }
        return false;
    }

    function isWeek(){
        var dateGrp = $('#SeasonSourceOption_m').attr('dateGrp');
        if('week_begin'==dateGrp){
            return true;
        }
        return false;
    }

     function isMonth(){
        var dateGrp = $('#SeasonSourceOption_m').attr('dateGrp');
        if('month_num'==dateGrp){
            return true;
        }
        return false;
    }
    
  	  function formatTime(time){
        return time.replace(/\-/g,'')
    }
    
    var zrUtil = require('zrender/tool/util');


    function getShowDays(){
        return compDataZoom_old.option.xAxis[0].data;
    }
    
    var compDataZoom_old;
    var legend_SelectedMap={};  //需要记忆图例的选择状态
    function hideDataZoom(){
        legend_SelectedMap=myChart.component.legend.getSelectedMap();
        compDataZoom_old=myChart.component.dataZoom;    //记忆缩放
        option_day.dataZoom.show=false;
        myChart.setOption(option_day,false);
    }

    function getIndexByName(data,name) {
        var dataLength = data.length;
        for (var i = 0; i < dataLength; i++) {
            if (data[i] == name || typeof data[i].value != 'undefined' && data[i].value == name) {
                return i;
            }
        }
        return -1;
    }
    function formatTime(time){
        return time;
    }

    function getAllDays(){
        return option_day.xAxis.data||option_day.xAxis[0].data;
    }

    var EC={
        echart:myChart,
        'show':show,
        resize:function(){myChart.resize();},
        hideDataZoom:hideDataZoom,
        getShowDays:getShowDays,
        getAllDays:getAllDays
    };
		//绑定change事件
         $("#source_option_m").change(function(){
             changeIndex(this);
             EC.show(businessName,2);
         });
       
        $("#refresh_cSeason_source_btn").click(function(){
            EC.show(businessName,2);
        });
    
        $(":button.btnSeasonSource_m[dateGrp]").click(function(){
            changeDateGrp(this);         
            EC.show(businessName,1);
        });

    return EC;
});

